const co = require('co');
const URL = require('url-parse');
const config = require('../config');
const log = require('../model/log');
const klgLogTemplate = require('../model/klgLogTemplate');
const logger = require('./logger').logger;
const db = require('../config/mongo');
const moment = require('moment-timezone');

const bus = require('servicebus').bus({
  url: config.app.rabbitmqUri,
  ack: true
});

bus.listen('koala.logCollector.saveReq', function (data) {
  data.interface = new URL(data.url).pathname;
  // logger.debug(data);
  const operation = co.wrap(function* () {
    return yield log.saveReq(data);
  });
  operation().then(function (result) {
    // logger.debug(result);
  }).catch(function (err) {
    logger.error(err);
  });
});

bus.listen('koala.logCollector.saveRes', function (data) {
  // logger.debug(data);
  const operation = co.wrap(function* () {
    return yield log.saveRes(data);
  });
  operation().then(function (result) {
    // logger.debug(result);
  }).catch(function (err) {
    logger.error(err);
  });
});

bus.listen('klg.log.collector.in.save', function (data) {
  // logger.debug(data);

  let service = (data.service || 'klg_project').toLowerCase();
  service = service.replace(new RegExp(/\-/g), '_');
  service += `_${moment().tz('Asia/Shanghai').format('YYYYMM')}`;
  const model = db.main.model(service, klgLogTemplate);

  const operation = co.wrap(function* () {
    return yield model.create(data);
  });
  operation().then(function (result) {
    // logger.error(result);
  }).catch(function (err) {
    logger.error(err);
  });
});

